<template>
  <div class="order-container">
    <!-- 店铺信息 -->
    <div class="store-info">
      <div class="store-name">
        <img src="https://stock-account.oss-cn-shenzhen.aliyuncs.com/dev/upload/2025-05-14/68244d33e75b0.png"
          style="width: 52rpx; height: 52rpx;object-fit: cover;border-radius: 50%;" mode="fill"></img>
        <span>{{ singleObj.store_name }}</span>
      </div>
    </div>

    <!-- 客户信息 -->
    <div class="customer-info" @click="switchAddress">
      <div class="customer-row">
        <div class="customer-avatar">
          <image src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-04/1746344971744.png" class="avatar-img">
          </image>
        </div>
        <div class="customer-data">
          <div class="customer-name">
            <span>{{ singleObj.current_address.consignee }}</span>
            <span class="mgl-40">{{ singleObj.current_address.mobile }}</span>
          </div>
          <div class="customer-address">
            {{ singleObj.current_address.address }}
          </div>
        </div>
        <div class="address-arrow">
          <text class="arrow-icon">></text>
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list" v-for="(item, index) in singleObj.detail" :key="index">
      <!-- 商品项 - 需要添加的商品 -->
      <div class="product-item" @click="selectBrand">
        <div class="product-required">*</div>
        <selectBrand style="width: 100%" v-model="item.brand_id" label="品牌" :options="item.selectOptions.brandList"
          placeholder="请选择品牌" @changeBrand="changeBrand(item, index)" />
      </div>

      <div class="product-item" @click="selectGoods">
        <div class="product-required">*</div>
        <SelectGoods style="width: 100%" v-model="item.goods_id" label="商品" :options="item.selectOptions.goodsList"
          placeholder="请选择商品" :title="`请先选品牌再选择商品`" @changeGoods="changeGoods(item, index)"
          @loadMore="loadMoreGoods(index)" />
      </div>

      <!-- <div class="product-item" @click="selectGoodsSpec">
        <div class="product-required">*</div>
        <selectSku style="width: 100%" v-model="item.sku_id" label="规格" :options="item.selectOptions.goodsSpecList"
          placeholder="请选择商品规格" :title="`请先选商品再选择规格`" @changeSku="changeSku($event, item, index)" />
      </div> -->

      <div class="product-item">
        <CascaderGoods
          label="规格"
          required
          placeholder="请选择商品规格"
          :options="item.selectOptions.goodsSpecList"
          v-model="item.sku_id"
          @change="changeSku($event, item, index)"
          style="flex: 1"
        />
      </div>

      <div class="product-item">
        <div class="product-required">*</div>
        <div class="product-label">数量</div>
        <div class="quantity-control">
          <div class="quantity-minus" @click="decreaseQuantity(item)">-</div>
          <!-- <input type="number" class="quantity-input" v-model="item.quantity" @change="changeQuantity(item)" /> -->
          <NumberInput
              v-model="item.quantity"
              :min="1"
              :max="999"
              class="quantity-input"
              @change="changeQuantity(item)"
            />
          <div class="quantity-plus" @click="increaseQuantity(item)">+</div>
        </div>
      </div>

      <div class="product-item no-required">
        <div class="product-label">备注</div>
        <input type="text" class="remark-input" placeholder="请输入备注内容" v-model="item.remark" />
      </div>

      <div class="price-info no-required">
        <div class="price-label">单价</div>
        <div class="price-value">¥
          <input type="digit" v-model="item.price" style="width: 200rpx" @change="changePrice(item)"></input>
        </div>
        <div class="total-price">总价: ¥{{ item.total_price }}</div>
      </div>

      <div class="action-buttons">
        <div class="add-button" @click="increaseAddedQuantity(index, item)">
          <gui-image src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427166764.png" :width="60"
            :height="60" />
          <text class="add-text">添加</text>
        </div>
        <div class="add-button" v-if="singleObj.detail.length > 1" @click="decreaseAddedQuantity(index)">
          <gui-image src="https://cphimg.leyoo888.com/dev/upload/supplier/2025-05-05/1746427171920.png" :width="60"
            :height="60" />
          <text class="add-text">删除</text>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="footer">
      <div class="total-section">
        合计: <text class="total-amount">¥{{ totalPrice }}</text>
        <text class="tax-info">(不含运费)</text>
      </div>
      <div class="submit-button" @click="debounce(submit, 800)">提交</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import { getShopBrand } from "@/api/store";
import { getGoodsList, getGoodsSpecList, proxyStoreOrder } from "@/api/goods";
import { getDefaultAddressApi } from "@/api/address";
import selectBrand from "@/component/goods/selectBrand.vue";
import SelectGoods from "@/component/goods/selectGoods.vue";
import { bc, showToast } from "@/utils/helper";
import cloneDeep from "lodash.clonedeep";
import CascaderGoods from "@/component/goods/cascaderGoods.vue";
import NumberInput from "@/component/numberInput/index.vue";
// 商品数量
const goodsObj = ref({
  brand_id: undefined,
  sku_id: undefined,
  goods_id: undefined,
  goods_spec_value_name: undefined,
  goods_spec_name: undefined,
  goods_value_name: undefined,
  quantity: 1,
  remark: "",
  price: 0,
  total_price: 0,
  selectOptions: {
    brandList: [],
    goodsList: [],
    goodsSpecList: [],
    goodsPage: {
      page: 1,
      limit: 99,
    },
  },
});
const singleObj = ref({
  shop_id: undefined,
  supplier_shop_id: undefined,
  store_name: undefined,
  current_address: {
    consignee: "请点击选择地址",
    address: "",
    mobile: "",
  },
  user_remark: "",
  detail: [cloneDeep(goodsObj.value)],
});

const totalPrice = computed(() => {
  return singleObj.value.detail.reduce((total, item) => {
    return bc(`${total} + ${item.total_price}`);
  }, 0);
});

// 增加数量
const increaseQuantity = (item) => {
  item.quantity += 1;
  item.total_price = bc(`${item.price} * ${item.quantity}`);
};

const changeQuantity = (item) => {
  item.quantity = isNaN(Number(item.quantity)) ? 1 : Number(item.quantity);
  item.total_price = bc(`${item.price} * ${item.quantity}`);
};

const changePrice = (item) => {
  item.price = Number(item.price).toFixed(2);
  item.total_price = bc(`${item.price}*${item.quantity}`);
};
// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity -= 1;
    item.total_price = bc(`${item.price} * ${item.quantity}`);
  }
};

// 增加已添加商品数量
const increaseAddedQuantity = async (index, item) => {
  singleObj.value.detail.splice(index, 0, cloneDeep({
    ...goodsObj.value,
    brand_id: item.brand_id,
    goods_id: item.goods_id,
  }));
  await getBrandList(index);
  if (item.brand_id) {
    await getGoodsListData(item.brand_id, index);
  }
  if (item.goods_id) {
    await getGoodsSpecListData(item.goods_id, index);
  }
};

// 减少已添加商品数量
const decreaseAddedQuantity = (index) => {
  singleObj.value.detail.splice(index, 1);
};

const switchAddress = () => {
  uni.navigateTo({
    url: `/pages/address/addresslist?is_proxy=1&supplier_shop_id=${singleObj.value.supplier_shop_id}`,
  });
};
//获取店铺的品牌
const getBrandList = async (index) => {
  const res = await getShopBrand({
    page: 1,
    limit: 99,
    supplier_shop_id: singleObj.value.supplier_shop_id,
  });
  singleObj.value.detail[index].selectOptions.brandList = res.map((item) => ({
    id: item.id,
    name: item.name,
  }));
};

const loadMoreGoods = (index) => {
  singleObj.value.detail[index].selectOptions.goodsPage.limit += 99;
  getGoodsListData(singleObj.value.detail[index].brand_id, index);
};
// 获取商品列表
const getGoodsListData = async (id, index) => {
  const res = await getGoodsList({
    ...singleObj.value.detail[index].selectOptions.goodsPage,
    brand_id: id,
  });
  singleObj.value.detail[index].selectOptions.goodsList = res.data.map(
    (item) => ({
      id: item.id,
      goods_name: item.goods_name,
      goods_image: item.goods_image,
      product_name: item.product_name,
      factory_price: item.factory_price,
    })
  );
};
// 获取商品规格列表
const getGoodsSpecListData = async (id, index) => {
  const res = await getGoodsSpecList({
    goods_id: id,
    supplier_shop_id: singleObj.value.supplier_shop_id,
    tree : 1,
  });
  singleObj.value.detail[index].selectOptions.goodsSpecList = res.sku;
};

const changeBrand = (item, index) => {
  getGoodsListData(item.brand_id, index);
  // 清空品牌以下的数据
  Object.assign(
    item,
    cloneDeep({
      ...goodsObj.value,
      brand_id: item.brand_id,
      selectOptions: {
        brandList: item.selectOptions.brandList || [],
        goodsList: [],
        goodsSpecList: [],
        goodsPage: {
          page: 1,
          limit: 99,
        },
      },
    })
  );
};

const changeGoods = (item, index) => {
  getGoodsSpecListData(item.goods_id, index);
  Object.assign(
    item,
    cloneDeep({
      ...goodsObj.value,
      brand_id: item.brand_id,
      goods_id: item.goods_id,
      goods_spec_value_name: item.goods_spec_value_name,
      goods_spec_name: item.goods_spec_name,
      goods_value_name: item.goods_value_name,
      selectOptions: {
        brandList: item.selectOptions.brandList || [],
        goodsList: item.selectOptions.goodsList || [],
        goodsSpecList: [],
        goodsPage: {
          page: 1,
          limit: 99,
        },
      },
    })
  );
};

const changeSku = (event, item, index) => {
  item.price = event.discount_price;
  item.total_price = bc(`${event.discount_price}*${item.quantity}`);
  item.goods_spec_name = event.goods_spec_name.join("??");
  item.goods_value_name = event.goods_spec_value_name.join("??");
  let str = "";
  event.goods_spec_name.forEach((item, indexSpe) => {
    str += item + "：" + event.goods_spec_value_name[indexSpe] + " ";
  });
  item.goods_spec_value_name = str;
};

const submit = async () => {
  console.log(singleObj.value.detail);
  const res = await proxyStoreOrder({
    shop_id: singleObj.value.shop_id,
    supplier_shop_id: singleObj.value.supplier_shop_id,
    address_id: singleObj.value.current_address.id,
    user_remark: "",
    detail: singleObj.value.detail.map((item) => ({
      brand_id: item.brand_id,
      goods_id: item.goods_id,
      sku_id: item.sku_id,
      quantity: item.quantity,
      price: item.price,
      goods_spec_value_name: item.goods_spec_value_name,
      goods_spec_name: item.goods_spec_name,
      goods_value_name: item.goods_value_name,
      remark: item.remark,
    })),
  });
  showToast("提交成功");
  uni.redirectTo({
    url: `/pages/success/success?totalPrice=${totalPrice.value}&type=proxy&id=${res}`,
  });
};

const getDefaultAddress = async () => {
  const res = await getDefaultAddressApi({
    supplier_shop_id: singleObj.value.supplier_shop_id,
  });
  res && (singleObj.value.current_address = res);
};

onUnload(() => {
  uni.$off("useAddress");
});
onShow(() => {
  uni.$on("useAddress", (address) => {
    singleObj.value.current_address = address;
  });
});
onLoad(async (options) => {
  singleObj.value.shop_id = options.id;
  singleObj.value.supplier_shop_id = options.supplier_shop_id; // 这才是供应商店铺的id
  singleObj.value.store_name = options.name;
  await getBrandList(0);
  // 获取默认地址
  await getDefaultAddress();
});
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

/* 店铺信息样式 */
.store-info {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1px solid #eee;
}

.store-name {
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4rpx;
}

/* 客户信息样式 */
.customer-info {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-top: 2rpx;
  border-bottom: 1px solid #eee;
}

.customer-row {
  display: flex;
  align-items: center;
}

.customer-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.customer-data {
  flex: 1;
}

.customer-name {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.customer-address {
  font-size: 26rpx;
  color: #666;
}

.address-arrow {
  width: 40rpx;
  text-align: right;
}

.arrow-icon {
  color: #ccc;
  font-size: 40rpx;
}

/* 商品列表样式 */
.product-list {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
}

.product-required {
  color: #f56c6c;
  font-size: 28rpx;
  margin-right: 5rpx;
}

.product-label {
  width: 100rpx;
  font-size: 28rpx;
  color: #333;
}

/* 数量控制样式 */
.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-minus,
.quantity-plus {
  width: 60rpx;
  height: 60rpx;
  line-height: 56rpx;
  text-align: center;
  border: 1px solid #ddd;
  font-size: 36rpx;
  color: #333;
  background-color: #f7f7f7;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 28rpx;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

/* 备注输入框样式 */
.remark-input {
  flex: 1;
  font-size: 28rpx;
  height: 60rpx;
  border: none;
}

/* 价格信息样式 */
.price-info {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.price-label {
  font-size: 28rpx;
  color: #666;
}

.price-value {
  font-size: 28rpx;
  color: #f56c6c;
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.total-price {
  margin-left: auto;
  font-size: 28rpx;
  color: #f56c6c;
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  padding: 20rpx 0;
}

.add-button,
.delete-button {
  display: flex;
  align-items: center;
  height: 80rpx;
  padding: 0 30rpx;
  background-color: #f7f7f7;
  border-radius: 4rpx;
  margin-right: 20rpx;
  gap: 10rpx;
}

.add-icon,
.delete-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.add-text,
.delete-text {
  font-size: 28rpx;
}

.delete-button {
  color: #f56c6c;
}

/* 底部结算栏样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.total-section {
  flex: 2;
  padding-left: 30rpx;
  font-size: 28rpx;
}

.total-amount {
  color: #f56c6c;
  font-weight: 500;
  font-size: 32rpx;
}

.tax-info {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.submit-button {
  flex: 1;
  height: 100%;
  background-color: #1989fa;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
}

.mgl-40 {
  margin-left: 40rpx;
}

.no-required {
  margin-left: 16rpx;
}
</style>
